package com.ntes.consumer1.controller;

import com.ntes.consumer1.service.DemoService;
import com.ntes.model.User;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by bjliuyue1 on 2017/5/19.
 */
@RestController
public class DemoController {

    @Autowired
    private DemoService demoService;

    @RequestMapping("/string")
    public String string(HttpServletRequest request) {
        return demoService.string(request.getParameter("name")) + " consumer1";
    }

    @RequestMapping("/user")
    public User user(HttpServletRequest request) {
        return demoService.user(request.getParameter("name"));
    }

    @RequestMapping("/getString")
    public String getString(HttpServletRequest request) {
        return demoService.getString(request.getParameter("name")) + " consumer1";
    }

    @RequestMapping("/userString")
    public String userString(HttpServletRequest request) {
        return demoService.userString(request.getParameter("name")) + " consumer1";
    }

    @Autowired
    private DiscoveryClient discoveryClient;

    @RequestMapping("/discovery")
    public String doDiscoveryService() {
        StringBuilder buf = new StringBuilder();
        List<String> serviceIds = discoveryClient.getServices();
        if (!CollectionUtils.isEmpty(serviceIds)) {
            for (String s : serviceIds) {
                System.out.println("serviceId:" + s);
                List<ServiceInstance> serviceInstances = discoveryClient.getInstances(s);
                if (!CollectionUtils.isEmpty(serviceInstances)) {
                    for (ServiceInstance si : serviceInstances) {
                        buf.append("[" + si.getServiceId() + " host=" + si.getHost() + " port=" + si.getPort() + " uri="
                                + si.getUri() + "]");
                    }
                }
                else {
                    buf.append("no service.");
                }
            }
        }
        return buf.toString();
    }
}
